﻿using System;
using System.Collections.Generic;
using System.Threading;
using System.Windows.Forms;
using System.IO;
using DuplicateFileFinder.Business;
using DuplicateFileFinder.Infrastructure;

namespace DuplicateFileFinder.Controller
{
    public class FormController
    {
        private Thread searchThread;
        private Thread hasherThread;

        public void StartScan(string path)
        {
            if (searchThread != null && searchThread.IsAlive) return;

            UIManager.Instance.ClearTreeView();
            UIManager.Instance.UpdateStatus("Starting...");

            var searchProcess = new SearchProcess();
            var threadStart = new ParameterizedThreadStart(searchProcess.StartSearch);
            (searchThread = new Thread(threadStart)).Start(path);

            var hasher = new FileComparisonProcessManager();
            var hashThreadStart = new ThreadStart(hasher.Start);
            (hasherThread = new Thread(hashThreadStart)).Start();
        }

        public void StopScan()
        {
            if (searchThread != null && hasherThread != null)
            {
                searchThread.Abort();
                hasherThread.Abort();
            }
            UIManager.Instance.UpdateStatus("Stopped.");
        }

        public bool Delete(IList<String> list)
        {
            if (searchThread != null && hasherThread != null && searchThread.IsAlive && hasherThread.IsAlive)
            {
                MessageBox.Show("Stop the running process first and then delete.");
                return false;
            }

            if (list.Count > 0)
            {
                if (MessageBox.Show("Are you sure You want to delete duplicate files? ", "Delete Duplicates", MessageBoxButtons.YesNo) == System.Windows.Forms.DialogResult.No)
                    return false;
            }

            var deleteThread = new Thread(new ParameterizedThreadStart(privateDelete));
            deleteThread.Start(list);

            return true;
        }

        private void privateDelete(object list)
        {
            foreach (string path in list as List<String>)
                File.Delete(path);

            UIManager.Instance.ClearTreeView();
        }

        public string GetPath()
        {
            var folderSelector = new FolderBrowserDialog();
            if (folderSelector.ShowDialog() != System.Windows.Forms.DialogResult.OK)
                return null;

            return folderSelector.SelectedPath;
        }
    }
}
